using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace stsdev {
  public class ApplicationPageBuilder {

    private static string SolutionSpecificLayoutsFolder = Globals.LayoutsFolder + @"\" + SolutionBuilder.SolutionName;

    private static void EnsureLayoutsFolder() {
       if (!Directory.Exists(Globals.TemplatesFolder)) {
        Directory.CreateDirectory(Globals.TemplatesFolder);
      }

      if (!Directory.Exists(Globals.LayoutsFolder)) {
        Directory.CreateDirectory(Globals.LayoutsFolder);
      }

      if (!Directory.Exists(SolutionSpecificLayoutsFolder)) {
        Directory.CreateDirectory(SolutionSpecificLayoutsFolder);
      }
    }

    public static void Create(string ApplicationPageName) {
      EnsureLayoutsFolder();
     
      string AspxFilePath = SolutionSpecificLayoutsFolder + @"\" + ApplicationPageName + ".aspx";
      if (!File.Exists(AspxFilePath)) {
        // create .aspx file for application page
        FileStream aspx_stream = File.Create(AspxFilePath);
        StreamWriter aspx_writer = new StreamWriter(aspx_stream);
        string aspx_content = Properties.Resources.ApplicationPageTemplate_aspx;
        aspx_content = aspx_content.Replace("@ApplicationPageName", ApplicationPageName);
        aspx_content = aspx_content.Replace("@SolutionName", SolutionBuilder.SolutionName);
        aspx_content = aspx_content.Replace("@FullAssemblyName", SolutionBuilder.FullAssemblyName);
        aspx_writer.Write(aspx_content);
        aspx_writer.Dispose();
        aspx_stream.Dispose();
        ProjectFileBuilder.AddSourceFile(AspxFilePath, SourceFileTypeEnum.None);
        // create code-behind .cs file for application page
        string CsFilePath = ApplicationPageName + ".cs";
        FileStream cs_stream = File.Create(CsFilePath);
        StreamWriter cs_writer = new StreamWriter(cs_stream);
        string cs_content = Properties.Resources.ApplicationPageTemplate_cs;
        cs_content = cs_content.Replace("@ApplicationPageName", ApplicationPageName);
        cs_content = cs_content.Replace("@SolutionName", SolutionBuilder.SolutionName);
        cs_writer.Write(cs_content);
        cs_writer.Dispose();
        aspx_stream.Dispose();
        ProjectFileBuilder.AddSourceFile(CsFilePath);
      }
    }
  }
}
